package com.cloudcc.mobile.bull;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.bull.utils.LocalUtil;
import com.cloudcc.mobile.dao.BullXiangGuanDao;
import com.cloudcc.mobile.dao.impl.BullXiangGuanImpl;
import com.cloudcc.mobile.dialog.BullListDialog;
import com.cloudcc.mobile.dialog.MakeTureDialog;
import com.cloudcc.mobile.entity.BullJxsNewJob;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.bean.NCheckIdBean;
import com.mypage.utils.UtilsShowDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GongniuAddShopActivity extends BaseActivity implements View.OnClickListener, IEventLife, BullListDialog.ChangeListener {

    @Bind(R.id.back)
    ImageButton back;
    @Bind(R.id.save)
    Button save;
    @Bind(R.id.et_shop_name)
    EditText etShopName;
    @Bind(R.id.tv_pro)
    TextView tvPro;
    @Bind(R.id.tv_city)
    TextView tvCity;
    @Bind(R.id.tv_qu)
    TextView tvQu;
    @Bind(R.id.et_persion_name)
    EditText etPersionName;
    @Bind(R.id.et_tel)
    EditText etTel;
    @Bind(R.id.et_remark)
    EditText etRemark;
    @Bind(R.id.mapView)
    MapView mapView;
    @Bind(R.id.textView)
    TextView textView;
    @Bind(R.id.et_address)
    TextView etAddress;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.tv_jxs)
            TextView tv_jxs;

    BaiduMap baiduMap;
    private boolean haveJxs = false;
    String name,id;
    String address,jw;
    String proId,cityId,quId,proName,cityName,quName,jxsId;
    private BullXiangGuanDao bullDao;
    private List<BullJxsNewJob> listJxs=new ArrayList<>();
    BullListDialog changeDialog;
    MakeTureDialog makeTureDialog;
    private UtilsShowDialog showDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_gongniu_add_shop;
    }
    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mapShow();
        initData();
        register();
    }

    private void initData() {
        showDialog = new UtilsShowDialog(this);
        makeTureDialog = new MakeTureDialog(this, R.style.DialogLoadingTheme);
        changeDialog = new BullListDialog(this, R.style.DialogLoadingTheme,this);
        bullDao = new BullXiangGuanImpl();
        BeauEventList.BullJxsEvent Event = new BeauEventList.BullJxsEvent();//查询经销商
        bullDao.BullgetJxs("Account", "", "khmc,name", Event);
        if("经销商".equals(getIntent().getStringExtra("title"))){
            tv_jxs.setText(getIntent().getStringExtra("name"));
            jxsId=getIntent().getStringExtra("id");
            Log.d("---",getIntent().getStringExtra("name")+getIntent().getStringExtra("id")+"--");
        }

    }
    public void onEventMainThread(BeauEventList.BullJxsEvent event) {

        listJxs = event.getData();
        if (listJxs != null && listJxs.size() != 0) {//查询到经销商
            haveJxs = true;
        } else {//没有查到经销商
            haveJxs = false;
        }
    }

    @OnClick({R.id.back, R.id.save,R.id.tv_jxs})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.save:
                save();
                break;
            case R.id.tv_jxs:
                if (haveJxs) {
                    changeDialog.show();
                    changeDialog.setDataJXS(listJxs);
                } else {
                    makeTureDialog.show();
                    makeTureDialog.setTitle("没有适合的经销商");
                }
                break;
        }
    }


    private void mapShow() {
        baiduMap=mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        LocalUtil localUtil=new LocalUtil();
        localUtil.getLoc(this, new LocalUtil.Res() {
            @Override
            public void getLoc(BDLocation location) {
                MyLocationData.Builder builder = new MyLocationData.Builder();
                builder.latitude(location.getLatitude());
                builder.longitude(location.getLongitude());
                MyLocationData data = builder.build();
                baiduMap.setMyLocationData(data);
                LatLng latLng =new LatLng(location.getLatitude(),location.getLongitude());
                MapStatusUpdate msu= MapStatusUpdateFactory.newLatLng(latLng);
                baiduMap.animateMapStatus(msu);
                jw=(location.getLongitude()+","+location.getLatitude());
                address=location.getProvince()+location.getCity()+ location.getDistrict()+location.getStreet()+location.getLocationDescribe();
                proName=location.getProvince();
                cityName=location.getCity();
                quName=location.getDistrict();
                etAddress.setText(location.getProvince()+location.getCity()+ location.getDistrict()+location.getStreet()+location.getLocationDescribe());

            }
        });
        mapView.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    scrollView.requestDisallowInterceptTouchEvent(false);
                }else{
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    scrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });

    }

   private void save(){
       String shopName=etShopName.getText().toString();
       String persionName=etPersionName.getText().toString();
       String tel=etTel.getText().toString();
       String address=etAddress.getText().toString();
       String remark=etRemark.getText().toString();
       if("".equals(shopName)){
           Toast.makeText(this, "门店名称不能为空", Toast.LENGTH_LONG).show();
           return;
       }
       if("".equals(persionName)){
           Toast.makeText(this, "门店负责人不能为空", Toast.LENGTH_LONG).show();
           return;
       }
       if("".equals(tel)){
           Toast.makeText(this, "联系电话不能为空", Toast.LENGTH_LONG).show();
           return;
       }
       if(jxsId==null){
           Toast.makeText(this, "请选择经销商", Toast.LENGTH_LONG).show();
           return;
       }
        Map<String,String> map=new HashMap<>();
        map.put("name",shopName);
        map.put("mdfzr",persionName);
        map.put("lxdh",tel);
        map.put("mddz",address);
        map.put("sf",proName);
        map.put("cs",cityName);
        map.put("xq",quName);
        map.put("dyjxs",jxsId);
        map.put("zt","正常");
        map.put("spzt","草稿");
        map.put("mddz",address);
       if("4.9E-324,4.9E-324".equals(jw)){
           Toast.makeText(this, "定位信息出错，请重新定位", Toast.LENGTH_SHORT).show();
           return;
       }
        map.put("dzzb",jw);
        if(!"".equals(remark)){
            map.put("bz",remark);
        }
        final Gson gson=new Gson();
        String data="["+gson.toJson(map)+"]";

       HttpUtils utils = new HttpUtils();
       RequestParams params = new RequestParams();
       params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
       params.addBodyParameter("serviceName", "insert");//普通插入服务
       params.addBodyParameter("objectApiName", "mendian");
       params.addBodyParameter("data", data);
       Log.d("---data",data);
       utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
               new RequestCallBack<String>() {

                   @Override
                   public void onFailure(HttpException arg0, String arg1) {
                       showDialog.onDismissLoadingDialog();
                       Toast.makeText(GongniuAddShopActivity.this, "新建门店出错", Toast.LENGTH_SHORT).show();
                       Log.d("---resError-------------------------", arg1);
                   }

                   @Override
                   public void onSuccess(ResponseInfo<String> arg0) {
                       Log.d("---res", arg0.result);
                       try {
                           JSONObject myJsonObject = new JSONObject(arg0.result);
                           String result=myJsonObject.getString("result");
                           String returnInfo=myJsonObject.getString("returnInfo");
                           if(result.equals("true")){
                              // Toast.makeText(GongniuAddShopActivity.this, "新建门店成功", Toast.LENGTH_SHORT).show();
                               RunTimeManager.getInstance().setGongniu("gnmd");
                           }else {
                               if(returnInfo.indexOf("：") != -1){
                                   returnInfo=returnInfo.substring(returnInfo.indexOf("：")+1,returnInfo.length());
                               }
                               Toast.makeText(GongniuAddShopActivity.this, returnInfo, Toast.LENGTH_SHORT).show();
                           }
                       } catch (Exception e) {
                           e.printStackTrace();
                           Toast.makeText(GongniuAddShopActivity.this, "新建门店出错", Toast.LENGTH_SHORT).show();
                       }
                       showDialog.onDismissLoadingDialog();
                       finish();
                   }
               });



    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
        unRegister();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    public void changeJxs(String names, String jxsId) {
        tv_jxs.setText(names);
        this.jxsId = jxsId;
    }

    @Override
    public void changeMd(String names, String id) {

    }

    @Override
    public void changeGzlx(String names) {

    }
}
